package com.kornero.auto.util;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public abstract class NetUtil {

    private static final Logger logger = LoggerFactory.getLogger(NetUtil.class);

    public static String doGetRequestViaExplorer(final String url) {
        logger.debug("doGetRequestViaExplorer(): Url = {}", url);

        final BlockingQueue<String> BLOCKING_QUEUE = new LinkedBlockingQueue<>();
        final Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                final Display display = new Display();
                final Shell shell = new Shell(display);
                shell.setLayout(new FillLayout());
                shell.setMinimumSize(400, 400);

                final Browser browser = new Browser(shell, SWT.NONE);
                browser.addProgressListener(new ProgressListener() {

                    @Override
                    public void changed(ProgressEvent event) {
                        final String html = browser.getText();
                        System.out.println("||||||||||||||||||||=" + html.length());
                    }

                    @Override
                    public void completed(ProgressEvent event) {
                        try {
                            final String html = browser.getText();
                            if (!html.contains("captcha")) {
                                if (browser.getText().length() > 100) {
                                    BLOCKING_QUEUE.put(browser.getText());
                                    shell.dispose();
                                } else {
                                    browser.refresh();
                                }
                            } else {
                                System.out.println("CAPTCHA!!!!");
                                browser.refresh();
                            }
                        } catch (InterruptedException e) {
                            logger.error("doGetRequestViaExplorer(): ", e);
                        }
                    }
                });

                browser.setVisible(true);
                browser.setJavascriptEnabled(true);

                browser.pack();
                shell.pack();
                shell.open();

                browser.setUrl(url);

                while (!shell.isDisposed()) {
                    if (!display.readAndDispatch()) {
                        display.sleep();
                    }
                }
                if (!display.isDisposed()) {
                    display.dispose();
                }
            }
        });
        t.start();

        try {
            return BLOCKING_QUEUE.take();
        } catch (InterruptedException e) {
            logger.error("doGetRequestViaExplorer():)", e);
        }
        return null;
    }

    public static String doGetStringRequest(final HttpResponse rsp) {
        try {
            if (null != rsp) {
                final HttpEntity entity = rsp.getEntity();
                if (null != entity) {
                    return EntityUtils.toString(entity);
                } else {
                    logger.error("doGetStringRequest(): HttpEntity is null!");
                }
            }
        } catch (IOException e) {
            logger.error("doGetStringRequest(): ", e);
        }
        return "";
    }

    public static HttpResponse doGetRequest(final String host, final String uri, final Header... headers) {
        logger.debug("doGetRequest(): host = {}, uri = {}, headers = {}", new Object[]{host, uri, Arrays.toString(headers)});
        final HttpHost target = new HttpHost(host);

        final DefaultHttpClient httpClient = new DefaultHttpClient();
        final HttpParams httpParams = httpClient.getParams();
        httpClient.setParams(getDefaultParameters(httpParams));

        final HttpGet req = new HttpGet(uri);
        setDefaultHeaders(req);
        req.setHeader("Host", host);
        req.setHeader("Referer", "http://" + host + uri);
        //req.setHeaders(headers);
        //req.setHeader("Cookie", "SPSI=656462f58cf8ca6648fc26f556f8cb34; PRID=GO");
        req.setHeader("Cookie", "SPSI=656462f58cf8ca6648fc26f556f8cb34; adOtr=64MH6; chcookie=1; autoru_sid=eaed71cdffaa42fa_1ac8eb8b2ad510efcdc3ca90ef4470ad; cookie_test=1; UTGv2=h4bd09b7c124107464f98e6878ba87a8b425; autoru_track=%7B%7D; PRLST=Oh; currency_key=RUR; __utma=1.925844902.1347652157.1347652157.1347652157.1; __utmb=1.4.10.1347652157; __utmc=1; __utmz=1.1347652157.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ym_visorc=b; RT=s=1347652935436&r=http%3A%2F%2Fcars.auto.ru%2Flist%2F%3Fcategory_id%3D15%26section_id%3D1%26subscribe_id%3D%26filter_id%3D%26submit%3D%25D0%259D%25D0%25B0%25D0%25B9%25D1%2582%25D0%25B8%26mark_id%3D52%26groups%5B%5D%3D1564%26groups%5B%5D%3D17637%26groups%5B%5D%3D17638%26year%5B1%5D%3D2008%26year%5B2%5D%3D%26color_id%3D%26price_usd%5B1%5D%3D230000%26price_usd%5B2%5D%3D380000%26currency_key%3DRUR%26body_key%3D%26run%5B1%5D%3D%26run%5B2%5D%3D%26engine_key%3D0%26engine_volume%5B1%5D%3D%26engine_volume%5B2%5D%3D%26drive_key%3D%26engine_power%5B1%5D%3D%26engine_power%5B2%5D%3D%26transmission_key%3D99%26used_key%3D5%26wheel_key%3D%26custom_key%3D%26available_key%3D%26change_key%3D%26owner_pts%3D%26stime%3D1%26country_id%3D1%26has_photo%3D0%26region%3D0%26region_id%3D87%26sort_by%3D2%26city_id%3D%26output_format%3D1%26client_id%3D1%26extras%5B1%5D%3D0%26extras%5B2%5D%3D0%26extras%5B3%5D%3D0%26extras%5B4%5D%3D0%26extras%5B5%5D%3D0%26extras%5B6%5D%3D0%26extras%5B7%5D%3D%26extras%5B8%5D%3D0%26extras%5B9%5D%3D0%26extras%5B10%5D%3D0%26extras%5B11%5D%3D0%26extras%5B12%5D%3D%26extras%5B13%5D%3D0%26extras%5B14%5D%3D0%26extras%5B15%5D%3D0%26extras%5B16%5D%3D0%26extras%5B17%5D%3D0%26extras%5B18%5D%3D%26extras%5B19%5D%3D%26extras%5B20%5D%3D%26extras%5B21%5D%3D%26extras%5B22%5D%3D%26extras%5B23%5D%3D0%26extras%5B24%5D%3D0%26extras%5B25%5D%3D%26extras%5B26%5D%3D%26extras%5B27%5D%3D0%26extras%5B28%5D%3D0%26extras%5B29%5D%3D");

        try {
            return httpClient.execute(target, req);
        } catch (IOException e) {
            logger.error("doGetRequest(): ", e);
        }
        return null;
    }

    private static HttpParams getDefaultParameters(final HttpParams httpParams) {
        httpParams.setParameter("Cache-Control", "max-age=0");
        httpParams.setParameter("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
        return httpParams;
    }

    private static void setDefaultHeaders(final HttpGet req) {
        req.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
        req.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        req.setHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
        req.setHeader("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.3");
        req.setHeader("Connection", "Keep-Alive");
        req.setHeader("Cache-Control", "max-age=0");
    }
}
